# -*- coding:utf-8 -*-

from fastapi import FastAPI
from contextlib import asynccontextmanager

from utils.logger import logger

from config.env import AppConfig, OpenApi

from core.middleware import handle_middleware
from core.exceptions import handle_exception

from config.database import init_create_table
from config.redis import redis_connect

from api import register_router

# 生命周期事件
@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info(f'{AppConfig.app_name}开始启动')
    await init_create_table()
    app.state.redis = await redis_connect()
    logger.info(f'{AppConfig.app_name}启动成功')
    yield
    await app.state.redis.close()
    logger.info(f'{AppConfig.app_name}关闭')

    

app = FastAPI(
    lifespan=lifespan,
    title=AppConfig.app_name,
    description=f'{AppConfig.app_name}接口文档',
    version=AppConfig.app_version,
    openapi_url=OpenApi.openapi_url,
    docs_url=OpenApi.openapi_ui_url,
    redoc_url=OpenApi.openapi_ui_redoc_url,
)

handle_middleware(app)
handle_exception(app)
register_router(app)

